package presentation.windows;

import java.awt.Font ;
import java.rmi.RemoteException ;
import java.text.SimpleDateFormat ;
import java.util.Date ;

import javax.swing.BorderFactory ;
import javax.swing.ButtonGroup ;
import javax.swing.JButton ;
import javax.swing.JCheckBox ;
import javax.swing.JLabel ;
import javax.swing.JOptionPane ;
import javax.swing.JPanel ;
import javax.swing.JPasswordField ;
import javax.swing.JRadioButton ;
import javax.swing.JTextField ;
import javax.swing.SwingWorker ;
import javax.swing.border.BevelBorder ;

import util.DuplicationException ;
import util.Log ;
import util.Subsystem ;

import com.toedter.calendar.JDateChooser ;



/**
 * The Class RegisterPanel is the panel for registering to the forum.
 */
public class RegisterPanel extends BasePanel
{

	private static final long serialVersionUID = 2009030180395190295L ;

	/** The register label. */
	private JLabel registerLabel;

	/** The Cancel button pressed when the user wants to clear the components. */
	private JButton CancelButton;

	/** The Register button , for registration. */
	private JButton RegisterButton;
	private JTextField firstNameField;
	private JLabel firstNameLabel;
	private JLabel optionsLabel;

	/** The password text field. */
	private JPasswordField passwordTextField;

	/** The verify password text field. */
	private JPasswordField verifyPasswordTextField;

	/** The user name text field. */
	private JTextField userNameTextField;

	/** The password label. */
	private JLabel passwordLabel;

	/** The verify password label. */
	private JLabel verifyPasswordLabel;

	private JTextField residenceField;
	private JLabel residenceLabel;
	private JRadioButton femaleButton;
	private JRadioButton maleButton;
	private ButtonGroup genderButtons;
	private JLabel genderLabel;

	private JLabel dobLabel;
	private JTextField lastNameField;
	private JLabel lastNameLabel;
	private JDateChooser dateOfBirth;
	private JCheckBox dobCheckBox;
	private JLabel obligatoryFieldsLabel;
	private JPanel dobPane;

	/** The user name label. */
	private JLabel userNameLabel;

	private String chosenGender;

	/**
	 * Instantiates a new view register panel.
	 * @param sharedData the shared data of all panels
	 */
	public RegisterPanel(final SharedUIData sharedData)
	{
		super(sharedData);
		this.setPreferredSize(new java.awt.Dimension(735, 566));
		this.chosenGender = "";
		this.initGUI();
	}

	/**
	 * Initiates all Gui of the register panel
	 */
	public void initGUI(){

		this.registerLabel = new JLabel();
		this.add(this.registerLabel);
		this.registerLabel.setText("Register");
		this.registerLabel.setBounds(307, 54, 151, 27);
		this.registerLabel.setFont(new Font("Californian FB",1,22));

		this.userNameLabel = new JLabel();
		this.add(this.userNameLabel);
		this.userNameLabel.setText("* username");
		this.userNameLabel.setFont(new Font("Californian FB",1,16));
		this.userNameLabel.setBounds(72, 136, 77, 30);

		this.passwordLabel = new JLabel();
		this.add(this.passwordLabel);
		this.passwordLabel.setText("* password");
		this.passwordLabel.setFont(new Font("Californian FB",1,16));
		this.passwordLabel.setBounds(72, 171, 83, 28);

		this.verifyPasswordLabel = new JLabel();
		this.add(this.verifyPasswordLabel);
		this.verifyPasswordLabel.setText("* verify password");
		this.verifyPasswordLabel.setFont(new Font("Californian FB",1,16));
		this.verifyPasswordLabel.setBounds(72, 203, 120, 30);

		this.userNameTextField = new JTextField();
		this.add(this.userNameTextField);
		this.userNameTextField.setBounds(201, 142, 170, 16);
		this.userNameTextField.setBorder(BorderFactory.createCompoundBorder(
				null,
				BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.passwordTextField = new JPasswordField();
		this.add(this.passwordTextField);
		this.passwordTextField.setBounds(201, 176, 170, 18);
		this.passwordTextField.setBorder(BorderFactory.createCompoundBorder(
				null,
				BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.verifyPasswordTextField = new JPasswordField();
		this.add(this.verifyPasswordTextField);
		this.verifyPasswordTextField.setBounds(201, 208, 170, 20);
		this.verifyPasswordTextField.setBorder(BorderFactory.createCompoundBorder(
				null,
				BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.RegisterButton = new JButton();
		this.add(this.RegisterButton);
		this.RegisterButton.setText("Register");
		this.RegisterButton.setBounds(287, 479, 85, 35);
		this.CancelButton = new JButton();
		this.add(this.CancelButton);
		this.CancelButton.setText("Reset");
		this.CancelButton.setBounds(428, 480, 84, 35);

		this.optionsLabel = new JLabel();
		this.add(this.optionsLabel);
		this.optionsLabel.setText("The next fields are optional and will be presented next to messages you write:");
		this.optionsLabel.setBounds(53, 262, 528, 14);
		this.optionsLabel.setFont(new Font("Californian FB",1,16));

		this.firstNameLabel = new JLabel();
		this.add(this.firstNameLabel);
		this.firstNameLabel.setText("First Name:");
		this.firstNameLabel.setBounds(72, 293, 89, 20);
		this.firstNameLabel.setFont(new Font("Californian FB",1,16));

		this.firstNameField = new JTextField();
		this.add(this.firstNameField);
		this.firstNameField.setBounds(167, 292, 140, 21);
		this.firstNameField.setBorder(BorderFactory.createCompoundBorder(
			null,
			BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.lastNameLabel = new JLabel();
		this.add(this.lastNameLabel);
		this.lastNameLabel.setText("Last Name:");
		this.lastNameLabel.setBounds(72, 329, 96, 17);
		this.lastNameLabel.setFont(new Font("Californian FB",1,16));

		this.lastNameField = new JTextField();
		this.add(this.lastNameField);
		this.lastNameField.setBounds(167, 325, 140, 18);
		this.lastNameField.setBorder(BorderFactory.createCompoundBorder(
			null,
			BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.dobLabel = new JLabel();
		this.add(this.dobLabel);
		this.dobLabel.setText("Date of birth:");
		this.dobLabel.setBounds(73, 359, 104, 21);
		this.dobLabel.setFont(new Font("Californian FB",1,16));

		this.dobPane = new JPanel();
		this.add(this.dobPane);
		this.dobPane.setBounds(165, 352, 138, 32);

		this.dateOfBirth = new JDateChooser();
		this.dobPane.add(this.dateOfBirth);


		this.genderLabel = new JLabel();
		this.add(this.genderLabel);
		this.genderLabel.setText("Gender:");
		this.genderLabel.setBounds(74, 394, 53, 20);
		this.genderLabel.setFont(new Font("Californian FB",1,16));

		this.genderButtons = new ButtonGroup();

		this.maleButton = new JRadioButton();
		this.add(this.maleButton);
		this.maleButton.setText("Male");
		this.maleButton.setBounds(165, 395, 58, 14);
		this.maleButton.setFont(new Font("Californian FB",1,16));
		this.genderButtons.add(this.maleButton);

		this.femaleButton = new JRadioButton();
		this.add(this.femaleButton);
		this.femaleButton.setText("Female");
		this.femaleButton.setBounds(239, 394, 80, 14);
		this.femaleButton.setFont(new Font("Californian FB",1,16));
		this.genderButtons.add(this.femaleButton);

		this.residenceLabel = new JLabel();
		this.add(this.residenceLabel);
		this.residenceLabel.setText("Residence:");
		this.residenceLabel.setBounds(74, 430, 73, 14);
		this.residenceLabel.setFont(new Font("Californian FB",1,16));

		this.residenceField = new JTextField();
		this.add(this.residenceField);
		this.residenceField.setBounds(165, 423, 140, 20);
		this.residenceField.setBorder(BorderFactory.createCompoundBorder(
			null,
			BorderFactory.createBevelBorder(BevelBorder.LOWERED)));

		this.obligatoryFieldsLabel = new JLabel();
		this.add(this.obligatoryFieldsLabel);
		this.obligatoryFieldsLabel.setText("The fields marked with * are obligatory:");
		this.obligatoryFieldsLabel.setBounds(53, 90, 274, 16);
		this.obligatoryFieldsLabel.setFont(new java.awt.Font("Californian FB",1,16));

		this.dobCheckBox = new JCheckBox();
		this.add(this.dobCheckBox);
		this.dobCheckBox.setText("Check this to save date");
		this.dobCheckBox.setBounds(309, 359, 172, 19);
		this.dobCheckBox.setFont(new java.awt.Font("Californian FB",1,12));

		this.dateOfBirth.setEnabled(false);

		//set button handlers:
		this.RegisterButton.addActionListener(new java.awt.event.ActionListener() {
	         @SuppressWarnings("synthetic-access")
			public void actionPerformed(@SuppressWarnings("unused") final java.awt.event.ActionEvent evt) {

	     		new SwingWorker<Void,Void>(){
	     			@Override
	     			protected Void doInBackground(){
	     				RegisterPanel.this.registerButtonHandler();
	     				return null;
	     			}
	     			@Override
	    			protected void done() { /* there is nothing to do here .. */ }
	    		}.execute();
	     }});


		//set button handlers:
		this.CancelButton.addActionListener(new java.awt.event.ActionListener() {
	         @SuppressWarnings("synthetic-access")
			public void actionPerformed(@SuppressWarnings("unused") final java.awt.event.ActionEvent evt) {
	        	 RegisterPanel.this.cancelButtonHandler();
	         }
		 });

		this.maleButton.addActionListener(new java.awt.event.ActionListener() {
	         @SuppressWarnings("synthetic-access")
			public void actionPerformed(@SuppressWarnings("unused") final java.awt.event.ActionEvent evt) {
	        	 RegisterPanel.this.maleButtonHandler();
	         }
		 });

		this.femaleButton.addActionListener(new java.awt.event.ActionListener() {
	         @SuppressWarnings("synthetic-access")
			public void actionPerformed(@SuppressWarnings("unused") final java.awt.event.ActionEvent evt) {
	        	 RegisterPanel.this.femaleButtonHandler();
	         }
		 });

		this.dobCheckBox.addActionListener(new java.awt.event.ActionListener() {
	         @SuppressWarnings("synthetic-access")
			public void actionPerformed(@SuppressWarnings("unused") final java.awt.event.ActionEvent evt) {
	        	 RegisterPanel.this.dobButtonHandler();
	         }
		 });

	}


	/**
	 * Cancel button handler. clears the components
	 */
	private void cancelButtonHandler()
	{
		this.userNameTextField.setText("");
		this.passwordTextField.setText("");
		this.verifyPasswordTextField.setText("");
		this.firstNameField.setText("");
		this.lastNameField.setText("");
		this.residenceField.setText("");
		this.dateOfBirth.setDate(new Date());
		this.genderButtons.clearSelection();
		this.chosenGender = "";
	}

	private void dobButtonHandler()
	{
		if (this.dobCheckBox.isSelected())
		{
			this.dateOfBirth.setEnabled(true);
		}
		else
		{
			this.dateOfBirth.setEnabled(false);
		}

	}

	private void femaleButtonHandler()
	{
		this.chosenGender = "Female";
	}

	private void maleButtonHandler()
	{
		this.chosenGender = "Male";
	}

	/**
	 * Register button handler pressed when the user want to register the forum
	 * The function also check the normality of the data.
	 */
	private void registerButtonHandler()
	{
		String username = this.userNameTextField.getText();
		String password = new String(this.passwordTextField.getPassword());
		String verifyPassword = new String (this.verifyPasswordTextField.getPassword());

		if((username.equals(""))||(password.equals("")) ||(verifyPassword.equals(""))){
			JOptionPane.showMessageDialog(RegisterPanel.this,
				"missing username or password!", "error occured", JOptionPane.ERROR_MESSAGE);
			this.userNameTextField.setText("");
			this.passwordTextField.setText("");
			this.verifyPasswordTextField.setText("");
		}
		else{
			try
			{
				if(password.equals(verifyPassword)){
					String firstName = this.firstNameField.getText();
					String lastName = this.lastNameField.getText();
					String residence = this.residenceField.getText();
					SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
					String dob = "";
					if (this.dobCheckBox.isSelected())
					{
						if (this.dateOfBirth.getDate()!=null)
						{
							dob = df.format(this.dateOfBirth.getDate());
						}
					}
					this.forum.register(username, password,firstName,lastName,dob,this.chosenGender,residence);
					JOptionPane.showMessageDialog(RegisterPanel.this, "Register successful");
					Log.getLogger(Subsystem.PRESENTATION_MODEL).finest("user " + username + " has registered successfully");
					this.notifyCompleted();
				}
				else
				{
					JOptionPane.showMessageDialog(RegisterPanel.this, "password and verify password is not match, please type again");
					this.passwordTextField.setText("");
					this.verifyPasswordTextField.setText("");
				}
			}
			catch (DuplicationException e)
			{
				JOptionPane.showMessageDialog(RegisterPanel.this,
					"Username already exists - choose new username", "error occured", JOptionPane.ERROR_MESSAGE);
			}
			catch (RemoteException e)
			{
				Log.getLogger(Subsystem.PRESENTATION_MODEL).info("Remote problems thrown in register panel");
				JOptionPane.showMessageDialog(RegisterPanel.this,
					"Communication problems, please try again", "error occured", JOptionPane.ERROR_MESSAGE);
			}

		}
	}


	/*public static void main(String[] args) throws RemoteException, NotFoundException, CorruptDataException, BadPasswordException{
		JFrame frame = new JFrame();
		frame.getContentPane().add(new ViewRegisterPanel());
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}*/
}
